package com.sanen.flyer.tool;

import com.sanen.flyer.common.CommonCallback;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * @author wsse
 * @date 2018-09-06 16:31
 */
public class ImageTool {
    /**
     * 通过图片路径加载图片
     *
     * @param path 图片路径
     * @return 图片
     */
    public static BufferedImage getImage(String path) {
        try {
            File file = new File(path);
            BufferedImage image = ImageIO.read(file);
            return image;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * 设置画笔旋转属性,并在回调方法执行后复原画笔旋转属性,旋转系数theta可通过getTheta()方法获取
     *
     * @param g     画笔
     * @param theta 旋转系数
     * @param x     旋转中心点x坐标
     * @param y     旋转中心点y坐标
     * @param cb    画笔旋转后需要执行的回调
     */
    public static void rotate(Graphics g, double theta, int x, int y, CommonCallback cb) {
        if (theta != 0) ((Graphics2D) g).rotate(theta, x, y);
        cb.callback();
        if (theta != 0) ((Graphics2D) g).rotate(-theta, x, y);
    }

    /**
     * 根据xy轴移动速度,计算旋转角度
     *
     * @param speedx
     * @param speedy
     * @return
     */
    public static double getTheta(double speedx, double speedy) {
        speedy = -speedy;
        if (speedx == 0) {
            if (speedy >= 0) return Math.toRadians(0);
            else return Math.toRadians(180);
        } else if (speedx > 0) {
            if (speedy == 0) return Math.toRadians(90);
            else if (speedy > 0) return Math.atan(speedx / speedy);//第一象限
            else return Math.toRadians(Math.toDegrees(Math.atan(speedx / speedy)) + 180);//第四象限
        } else {
            if (speedy == 0) return Math.toRadians(270);
            if (speedy >= 0) return Math.atan(speedx / speedy);//第二象限
            else return Math.toRadians(Math.toDegrees(Math.atan(speedx / speedy)) + 180);
        }//第三象限
    }

    /**
     * 根据xy轴移动速度,计算旋转角度
     *
     * @param speedx
     * @param speedy
     * @param orientation 图片朝向, 1:向上  -1 向下
     * @return
     */
    public static double getTheta(double speedx, double speedy, int orientation) {
        if (orientation == 0) return 0;
        return getTheta(speedx * orientation, speedy * orientation);
    }
}
